import socket
import struct
import threading

def handle_client(client_socket, save_dir):
    try:
        # 接收固定长度头信息
        header = client_socket.recv(132)
        # 128sl
        filename, filesize = struct.unpack('128sl', header)
        filename = filename.decode().strip('\x00')
        save_path = f"{save_dir}/client-{filename}"

        # 接收文件内容
        with open(save_path, 'wb') as f:
            recv_size = 0
            while recv_size < filesize:
                chunk = client_socket.recv(4096)
                if not chunk: break
                f.write(chunk)
                recv_size += len(chunk)
                progress = recv_size / filesize * 100
                print(f"已接收：{recv_size}/{filesize}")
                print(f"进度：{progress:.2f}%")
        print(f"✅ 文件接收完成: {filename}")
        print(f'保存为：client-{filename}')
    finally:
        client_socket.close()

def start_server(save_dir, port=8888):
    server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)



    ip = socket.gethostname()

    server_socket.bind((ip, port))
    server_socket.listen(5)
    print(f"🖥️ 服务端启动，端口: {port}")
    while True:
        client_sock, addr = server_socket.accept()
        print(f"📩 客户端连接: {addr}")
        thread = threading.Thread(target=handle_client, args=(client_sock, save_dir))
        thread.start()


start_server('./')



















































































